package com.example.tourpal.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * @author wuliqing
 */
public class ServiceDataLoader {
	public static final int MAX_FAILCOUNT = 3;
	public final static String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36";

	public static String fecthUrl(String url) {
		String lineText;
		StringBuilder sb = new StringBuilder();
		InputStreamReader isr = null;
		int failCount = 0;
		do {
			try {
				HttpGet get = new HttpGet(url);
				HttpClient httpClient = new DefaultHttpClient();
				HttpResponse response = httpClient.execute(get);
				int status = response.getStatusLine().getStatusCode();
				HttpEntity entity = response.getEntity();
				if (status != HttpStatus.SC_OK || entity == null) {
					return null;
				}
				isr = new InputStreamReader(entity.getContent());
				BufferedReader bufReader = new BufferedReader(isr);
				while ((lineText = bufReader.readLine()) != null) {
					sb.append(lineText);
				}
				break;
			} catch (Exception e) {
				failCount++;
				e.printStackTrace();
			} finally {
				try {
					if (isr != null) {
						isr.close();
					}
				} catch (IOException e) {

				}
			}
		} while (failCount < MAX_FAILCOUNT);
		return sb.toString();
	}

	public static String sendGetRequest(String path, Map<String, String> params)
			throws Exception {
		StringBuilder sb = new StringBuilder(path);
		sb.append('?');
		// ?method=save&title=435435435&timelength=89&
		for (Map.Entry<String, String> entry : params.entrySet()) {
			sb.append(entry.getKey()).append('=')
					.append(URLEncoder.encode(entry.getValue(), "UTF-8"))
					.append('&');
		}
		sb.deleteCharAt(sb.length() - 1);

		String lineText;
		StringBuilder sb1 = new StringBuilder();
		InputStreamReader isr = null;
		int failCount = 0;
		do {
			try {
				HttpGet get = new HttpGet(sb.toString());
				HttpClient httpClient = new DefaultHttpClient();
				HttpResponse response = httpClient.execute(get);
				int status = response.getStatusLine().getStatusCode();
				HttpEntity entity = response.getEntity();
				if (status != HttpStatus.SC_OK || entity == null) {
					return null;
				}
				isr = new InputStreamReader(entity.getContent());
				BufferedReader bufReader = new BufferedReader(isr);
				while ((lineText = bufReader.readLine()) != null) {
					sb1.append(lineText);
				}
				break;
			} catch (Exception e) {
				failCount++;
				e.printStackTrace();
			} finally {
				try {
					if (isr != null) {
						isr.close();
					}
				} catch (IOException e) {

				}
			}
		} while (failCount < MAX_FAILCOUNT);
		return sb1.toString();
	}

	public static String sendPostRequest(String path, Map<String, String> params)
			throws Exception {
		StringBuilder sb = new StringBuilder(path);
		sb.append('?');
		for (Map.Entry<String, String> entry : params.entrySet()) {
			sb.append(entry.getKey()).append('=')
					.append(URLEncoder.encode(entry.getValue(), "UTF-8"))
					.append('&');
		}
		sb.deleteCharAt(sb.length() - 1);

		String lineText;
		StringBuilder sb1 = new StringBuilder();
		InputStreamReader isr = null;
		int failCount = 0;
		do {
			try {
				HttpPost httpost = new HttpPost(sb.toString());
				HttpClient httpClient = new DefaultHttpClient();
				HttpResponse response = httpClient.execute(httpost);
				HttpEntity entity = response.getEntity();

				int status = response.getStatusLine().getStatusCode();
				if (status != HttpStatus.SC_OK || entity == null) {
					return null;
				}
				isr = new InputStreamReader(entity.getContent());
				BufferedReader bufReader = new BufferedReader(isr);
				while ((lineText = bufReader.readLine()) != null) {
					sb1.append(lineText);
				}
				break;
			} catch (Exception e) {
				failCount++;
				e.printStackTrace();
			} finally {
				try {
					if (isr != null) {
						isr.close();
					}
				} catch (IOException e) {

				}
			}
		} while (failCount < MAX_FAILCOUNT);
		return sb1.toString();
	}

	/**
	 * @param nvs
	 * @param url
	 * @param cookie
	 * @return
	 */
	public static String postDataToServer(List<NameValuePair> nvs, String url,
			String cookie) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpPost httpost = new HttpPost(url);
		// httpost.setHeader("Cookie", cookie);
		StringBuilder sb = new StringBuilder();
		InputStreamReader isr = null;
		int failCount = 0;
		do {
			try {
				if (nvs != null)
					httpost.setEntity(new UrlEncodedFormEntity(nvs, HTTP.UTF_8));
				HttpResponse response = httpclient.execute(httpost);
				HttpEntity entity = response.getEntity();
				int status = response.getStatusLine().getStatusCode();
				if (status != HttpStatus.SC_OK || entity == null) {
					return null;
				}
				isr = new InputStreamReader(entity.getContent());
				BufferedReader bufReader = new BufferedReader(isr);
				String lineText = null;
				while ((lineText = bufReader.readLine()) != null) {
					sb.append(lineText);
				}
			} catch (Exception e) {
				failCount++;
				e.printStackTrace();
			} finally {
				try {
					if (isr != null) {
						isr.close();
					}
				} catch (IOException e) {

				}
				httpclient.getConnectionManager().shutdown();
			}
		} while (failCount < MAX_FAILCOUNT);
		return sb.toString();
	}

	public static String putDataToServer(List<NameValuePair> nvs, String url,
			String cookie) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpPut httput = new HttpPut(url);
		StringBuilder sb = new StringBuilder();
		InputStreamReader isr = null;
		int failCount = 0;
		do {
			try {
				if (nvs != null)
					httput.setEntity(new UrlEncodedFormEntity(nvs, HTTP.UTF_8));
				HttpResponse response = httpclient.execute(httput);
				HttpEntity entity = response.getEntity();
				int status = response.getStatusLine().getStatusCode();
				if (status != HttpStatus.SC_OK || entity == null) {
					return null;
				}
				isr = new InputStreamReader(entity.getContent());
				BufferedReader bufReader = new BufferedReader(isr);
				String lineText = null;
				while ((lineText = bufReader.readLine()) != null) {
					sb.append(lineText);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (isr != null) {
						isr.close();
					}
				} catch (IOException e) {

				}
				httpclient.getConnectionManager().shutdown();
			}
		} while (failCount < MAX_FAILCOUNT);
		return sb.toString();
	}

	public static String deleteDataToServer(String path,
			Map<String, String> params) throws Exception {
		StringBuilder sb = new StringBuilder(path);
		sb.append('?');
		for (Map.Entry<String, String> entry : params.entrySet()) {
			sb.append(entry.getKey()).append('=')
					.append(URLEncoder.encode(entry.getValue(), "UTF-8"))
					.append('&');
		}
		sb.deleteCharAt(sb.length() - 1);
		StringBuilder sb1 = new StringBuilder();
		InputStreamReader isr = null;
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			MyHttpDelete delete = new MyHttpDelete(sb.toString());
			// delete.setEntity(new UrlEncodedFormEntity(nvs));
			HttpResponse response = httpClient.execute(delete);
			HttpEntity entity = response.getEntity();
			int status = response.getStatusLine().getStatusCode();
			if (status != HttpStatus.SC_OK || entity == null) {
				return null;
			}
			isr = new InputStreamReader(entity.getContent());
			BufferedReader bufReader = new BufferedReader(isr);
			String lineText = null;
			while ((lineText = bufReader.readLine()) != null) {
				sb1.append(lineText);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (isr != null) {
					isr.close();
				}
			} catch (IOException e) {

			}
		}
		return sb1.toString();
	}

	public static String deleteDataToServer(List<NameValuePair> nvs, String url) {
		StringBuilder sb = new StringBuilder();
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			MyHttpDelete delete = new MyHttpDelete(url);
			delete.setEntity(new UrlEncodedFormEntity(nvs));
			HttpResponse response = httpClient.execute(delete);
			HttpEntity entity = response.getEntity();
			int status = response.getStatusLine().getStatusCode();
			if (status != HttpStatus.SC_OK || entity == null) {
				return null;
			}
			InputStreamReader isr = new InputStreamReader(entity.getContent());
			BufferedReader bufReader = new BufferedReader(isr);
			String lineText = null;
			while ((lineText = bufReader.readLine()) != null) {
				sb.append(lineText);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	public static HttpGet getHttpGet(String url) {
		HttpGet get = new HttpGet(url);
		get.setHeader("User-Agent", USER_AGENT);
		if (Pattern.matches("^http://essay.*", url)) {
			get.setHeader("Host", "essay.oss.aliyuncs.com");
			get.setHeader("Referer", "http://chuansongme.com");
		} else if (Pattern.matches("http://pic\\.qiushibaike\\.com", url)) {
			get.setHeader("Host", "pic.qiushibaike.com");
		}
		return get;
	}

	/**
	 * 
	 * 
	 * @param imgUrl
	 * */
	public static Bitmap downNetImage(String url) {
		Bitmap bitmap = null;
		HttpClient client = new DefaultHttpClient();
		HttpGet get = getHttpGet(url);
		int failCount = 1;
		do {
			try {
				HttpResponse response = client.execute(get);
				HttpEntity entity = response.getEntity();
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK
						&& entity != null) {
					bitmap = BitmapFactory.decodeStream(entity.getContent());
				}
				break;
			} catch (Exception e) {
				failCount++;
			}
		} while (failCount < MAX_FAILCOUNT);

		return bitmap;
	}

}
